package cn.csxw.openchina.dagger2.presenter;

import cn.csxw.openchina.entity.ResultState;
import cn.csxw.openchina.entity.bean.OsChinaBean;
import cn.csxw.openchina.interfaces.IOSChinaServer;
import cn.csxw.openchina.utils.Global;
import okhttp3.Headers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by hp on 2017/1/12.
 * 访问网络的基类
 */

public abstract class BasePresenter {
    protected final IOSChinaServer mOsChinaServer;
    protected ResultState mResultState;
    protected boolean isRefresh  = false;

    public BasePresenter(){
        mOsChinaServer = Global.mOsChinaServer;
    }

    public void setIsRefresh(){
        this.isRefresh = true;
    }

    protected Callback mCallback = new Callback<OsChinaBean>() {
        @Override
        public void onResponse(Call<OsChinaBean> call, Response<OsChinaBean> response) {
            //成功连上服务器
            Headers headers = response.headers();
            String s = headers.get("Set-Cookie");
            Global.setCookie(s);
            if(response.body() == null){
                mResultState = ResultState.LOAD_EMPTY;
                if(mOnResultStateListener != null){
                    mOnResultStateListener.onStateEmpty(mResultState);
                }
            }else{
                OsChinaBean data = response.body();
                if(data.user!=null){
                    String uid = data.user.uid;
                  Global.setUserUid(uid);
                }
                mResultState = ResultState.LOAD_SUCCESS;
                processData(data);
                if(mOnResultStateListener != null){
                    mOnResultStateListener.onStateSuccess(mResultState);
                }
            }
        }
        @Override
        public void onFailure(Call<OsChinaBean> call, Throwable t) {
            //连接服务器失败
            t.printStackTrace();
            mResultState = ResultState.LOAD_ERROR;
            if(mOnResultStateListener != null){
                mOnResultStateListener.onStateError(t, mResultState);
            }
            Global.showToast("网络连接失败");
        }
    };

    protected abstract void processData(OsChinaBean data);

    public abstract void callNetWork(Object... params);
    private  OnResultStateListener mOnResultStateListener;
    public interface OnResultStateListener{
        void onStateError(Throwable t,ResultState errorState);
        void onStateSuccess(ResultState successState);
        void onStateEmpty(ResultState emptyState);
    }

    public void setOnResultStateListener(OnResultStateListener onResultStateListener){
            mOnResultStateListener =onResultStateListener;
    }



    //提供一个方法判断是否还有更多数据
    public boolean hasMoreData(OsChinaBean data){
        return   data.pagesize==0?false:true;
    }
}
